package org.frame.auth.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletResponse;

import org.frame.auth.service.ILoginService;
import org.frame.common.core.AjaxResult;
import org.frame.common.core.Base64;
import org.frame.common.core.IdUtils;
import org.frame.common.core.VerifyCodeUtils;
import org.frame.common.core.constants.Constants;
import org.frame.common.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Slf4j
@RestController
public class LoginController {
	@Autowired
	private ILoginService loginService;

	@Autowired
	private RedisCache redisCache;

	/**
	 * 登录方法
	 * 
	 * @param username 用户名
	 * @param password 密码
	 * @param captcha  验证码
	 * @param uuid     唯一标识
	 * @return 结果
	 */
	@PostMapping("/login")
	public AjaxResult login(String username, String password, String code, String uuid) {
		AjaxResult ajax = AjaxResult.success();
		// 生成令牌
		String token = loginService.login(username, password, code, uuid);
		ajax.put(Constants.TOKEN, token);
		return ajax;
	}

	/**
	 * 生成验证码
	 */
	@GetMapping("/captchaImage")
	public AjaxResult getCode(HttpServletResponse response) {
		ByteArrayOutputStream stream = null;
		try {
			// 生成随机字串
			String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
			log.debug("验证码：{}", verifyCode);
			// 唯一标识
			String uuid = IdUtils.simpleUUID();
			String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
	
			redisCache.setCacheObject(verifyKey, verifyCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
			// 生成图片
			int w = 111, h = 36;
			stream = new ByteArrayOutputStream();
			VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
		
			AjaxResult ajax = AjaxResult.success();
			ajax.put("uuid", uuid);
			ajax.put("img", Base64.encode(stream.toByteArray()));
			return ajax;
		} catch (Exception e) {
			log.debug("生成验证码异常", e);
			return AjaxResult.error(e.getMessage());
		} finally {
			try {
				if(stream != null) {
					stream.close();
				}
			} catch (IOException e) {
				log.debug("生成验证码关闭流异常", e);
			}
		}
	}

}
